package servlets;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
import org.apache.tools.zip.ZipOutputStream;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.Path;
import org.eclipse.swt.widgets.Display;

import sssex.Activator;
import sssex.editors.MultiPageEditor;
import webx.actions.BookMarkLink;
import webx.actions.BoolMarkArea;
import webx.actions.GetSelectedFilesRunnable;
import webx.actions.OpenFileInnerRunnable;
import webx.actions.OpenFileRunnable;
import webx.actions.OperEditorRunnable;
import webx.actions.ScreenShotTest;
import webx.actions.SearchFileRunnable;

public class EclipseServlet extends HttpServlet {
	
	public final String SEARCH_FILE = "searchfile" ; // Eclipse搜索文件指令
	public final String OPEN_FILE = "openfile"; // Eclipse打开文件指令
	public final String SAVE_FILE = "savefile"; // Eclipse保存文件指令
	public final String FILE = "file"; //编辑器打开file
	public final String GET_SELECTED_FILES = "getSelectedFiles";
	public final String GET_EDITOR_VALUE = "getEditorValue";
	public final String SET_EDITOR_VALUE = "setEditorValue";
	public final String SET_EDITOR_UNDO = "setEditorUndo";
	public final String EDITOR_DO_SAVE = "editorDoSave";
	public final String CREATE_A_FILE = "createAFile"; // 创建一个文件
	public final String GET_BOOK_MARK_LINKS = "getBookMarkLinks"; // 根据添加的BookMark创建文件链接
	public final String CLEAR_BOOK_MARK_LINKS = "clearBookMarkLinks"; // 清空BOOKMARKLINKS的缓存
	public final String OPEN_INNER = "openInner"; // 同一窗口中打开
	public final String SCREEN_SHOOT="cutScreen"; // 屏幕截图
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		resp.setCharacterEncoding("UTF-8");
		String type = req.getParameter("type");
		//System.out.println(type);
		
		System.out.println("type：===============> "+type);
		if(OPEN_INNER.equals(type)){
			String pagepath = req.getParameter("pagepath");
			String rownum = req.getParameter("row");
			System.out.println("pagepath："+pagepath);
			Display.getDefault().syncExec(new OpenFileInnerRunnable(pagepath,rownum));
		}
		
		if(SEARCH_FILE.equals(type)){
			String scope = req.getParameter("scope");
			String string = req.getParameter("string");
			Display.getDefault().syncExec(new SearchFileRunnable(scope,string));
		}
		// select * from r_task where  (Prin_UserID like '%20161007094336264%' or JoinUsersID like '%20161007094336264%')  and TASK_STATE='未完成'

		if(OPEN_FILE.equals(type)){
			String pagepath = req.getParameter("pagepath");
			String rownum = req.getParameter("row");
			System.out.println("pagepath："+pagepath);
			Display.getDefault().syncExec(new OpenFileRunnable(pagepath,rownum));
		} 
		
		if(GET_SELECTED_FILES.equals(type)){
			Map result = new HashMap();
			Display.getDefault().syncExec(new GetSelectedFilesRunnable(result));
			System.out.println("result："+result);
			String resultStr = result.get("result")==null?"":(String)result.get("result");
			resp.getWriter().write(resultStr);
			resp.getWriter().close();
		}
		//http://localhost:2016/manager/Dev.do?type=savefile
		//System.out.println("type："+type);
		
		if(EDITOR_DO_SAVE.equals(type)){
			Map result = new HashMap();
			result.put("TYPE", "DOSAVE");
			Display.getDefault().syncExec(new OperEditorRunnable(result));
			String resultStr = result.get("result")==null?"":(String)result.get("result");
			//System.out.println("SET_EDITOR_UNDO:"+resultStr);
			resp.getWriter().write(resultStr);
			resp.getWriter().close();
		}
		
		if(SET_EDITOR_UNDO.equals(type)){
			Map result = new HashMap();
			result.put("TYPE", "UNDO");
			Display.getDefault().asyncExec(new OperEditorRunnable(result));
			String resultStr = result.get("result")==null?"":(String)result.get("result");
			System.out.println("SET_EDITOR_UNDO:"+resultStr);
			resp.getWriter().write(resultStr);
			resp.getWriter().close();
		}
		
		String filePath = req.getParameter("editfile");
		//System.out.println("filePath:"+new String(filePath.getBytes("iso-8859-1"),"iso-8859-1"));
		
		//System.out.println("filePath:"+filePath);
		if(null!=filePath){
			filePath = java.net.URLDecoder.decode(filePath,"UTF-8"); 
			IResource iresource = ResourcesPlugin.getWorkspace().getRoot().findMember(new Path(filePath));
			String exten = iresource.getFileExtension();
			if("eclick".equals(exten)){
				File editfile = iresource.getLocation().makeAbsolute().toFile().getAbsoluteFile();
				// 
				try{
			        ZipFile zisf = new ZipFile(editfile);
			        
			        Enumeration<ZipEntry> entries = zisf.getEntries();
			        while(entries.hasMoreElements()){
			        	ZipEntry entry = entries.nextElement();
			        	if(!"daimabiji.html".equals(entry.getName())){
			        		String targetpath = Activator.plugin_path+"/webapps/manager/clientdata/"+entry.getName();
			        		File jpg = new File(targetpath);
			        		if(!jpg.exists()){
			        			InputStream ins = zisf.getInputStream(entry);
					        	byte[] jpgEntry = new byte[(int)entry.getSize()];
					        	System.out.println();
					        	int i = 0;
					        	FileOutputStream fos = new FileOutputStream(jpg);
					        	while((i = ins.read(jpgEntry))>0){
					        		fos.write(jpgEntry,0,i);
					        	}
					        	ins.close();
					        	fos.flush();
					        	fos.close();
			        		}
			        	}
			        	// System.out.println(zip.getName()+zip.getExtra().length);
			        }
			        ZipEntry entry = zisf.getEntry("daimabiji.html");
			        if(entry!=null){
			        	InputStream ins = zisf.getInputStream(entry);
			        	byte[] daimabiji = null;
			        	//
			        	BufferedInputStream bufin = new BufferedInputStream(ins);
			    		int buffSize = 1024;
			    		ByteArrayOutputStream out = new ByteArrayOutputStream(buffSize);
			    		byte[] temp = new byte[buffSize];
			    		int size = 0;
			    		while ((size = bufin.read(temp)) != -1) {
			    			out.write(temp, 0, size);
			    		}
			    		bufin.close();
			    		daimabiji = out.toByteArray();
			        	//
			        	ins.close();
			        	zisf.close();
			        	resp.getWriter().write(new String(daimabiji,"UTF-8"));
						resp.getWriter().close();
			        }else{
			        	resp.getWriter().write("");
						resp.getWriter().close();
			        }
		    	}catch(Exception ex){
		    		ex.printStackTrace();
		    		if(ex.getMessage().equals("archive is not a ZIP archive")){
		    			FileInputStream fis = new FileInputStream(editfile);
						byte[] data = new byte[fis.available()];
						fis.read(data);
						fis.close();
						resp.getWriter().write(new String(data,"UTF-8"));
						resp.getWriter().close();
		    		}
		    	}
				// 
				
			}
		}
		
		if(CREATE_A_FILE.equals(type)){
			String file_Path = req.getParameter("filePath");
			String fileContent = req.getParameter("fileContent");
			byte[] utf8content = fileContent.getBytes("UTF-8");
			FileOutputStream fos = new FileOutputStream(file_Path);
			fos.write(utf8content);
			fos.flush();
			fos.close();
			Display.getDefault().syncExec(new Runnable(){
				 public void run() {
					try{
						
					}catch(Throwable e){
						e.printStackTrace();
					}
		         }
			});
		}
		
		if(GET_BOOK_MARK_LINKS.equals(type)){
			StringBuffer sb = new StringBuffer("[");
			if(BoolMarkArea.link!=null && BoolMarkArea.link.size()>0){
				for(int i=0;i<BoolMarkArea.link.size();i++){
					BookMarkLink link = BoolMarkArea.link.get(i);
					String lineNumber = link.getLineNumber();
					String location = link.getLocation();
					String message = link.getMessage();
					sb.append("{");
					sb.append("\"row\":\""+lineNumber+"\",");
					sb.append("\"path\":\""+location+"\",");
					sb.append("\"msg\":\""+message.replace("\"", "\\\"")+"\"");
					sb.append("}");
					if(i!=BoolMarkArea.link.size()-1){
						sb.append(",");
					}
				}
			}
			sb.append("]");
			BoolMarkArea.link.clear();
			System.out.println(sb.toString());
			resp.getWriter().write(sb.toString());
			resp.getWriter().close();
		}
		if(CLEAR_BOOK_MARK_LINKS.equals(type)){
			BoolMarkArea.link.clear();
			resp.getWriter().write("OK");
			resp.getWriter().close();
		}
		
		if(SCREEN_SHOOT.equals(type)){
			ScreenShotTest.saveWebPath = req.getSession().getServletContext().getRealPath("");
			// System.out.println("ScreenShotTest.saveWebPath:"+ScreenShotTest.saveWebPath);
			String jpgName = ScreenShotTest.cutScreen();
			if(jpgName==null){
				jpgName = "";
			}
			resp.getWriter().write(jpgName);
			// System.out.println(editor.getAbsolutePath());
		}
		
	}

	@SuppressWarnings({ "rawtypes", "unchecked", "unused" })
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		resp.setCharacterEncoding("UTF-8");		
		String type = req.getParameter("type"); // System.out.println("type"+type);
		System.out.println("type：===============> "+type);
		if(SET_EDITOR_VALUE.equals(type)){
			String filePath = req.getParameter("editfile");
			Map result = new HashMap();
			result.put("TYPE", "SET");
			result.put("text", req.getParameter("text"));
			Display.getDefault().asyncExec(new OperEditorRunnable(result));
			MultiPageEditor multi = MultiPageEditor.multiPageEditorMap.get(filePath);
			//String resultStr = result.get("result")==null?"":(String)result.get("result");
			//System.out.println("GET_EDITOR_VALUE1111:"+resultStr);
			//multi.doc.set(resultStr);
			resp.getWriter().write("");
			resp.getWriter().close();
		}
		if(GET_EDITOR_VALUE.equals(type)){
			//IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
			String filePath = req.getParameter("editfile");
			System.out.println("filePath:"+new String(filePath.getBytes("iso-8859-1"),"iso-8859-1"));
			filePath = java.net.URLDecoder.decode(filePath,"UTF-8"); 
			System.out.println("GET_EDITOR_VALUE - start: ");
			Map result = new HashMap();
			result.put("TYPE", "GET");
			// Display.getDefault().syncExec(new OperEditorRunnable(result));
			MultiPageEditor multi = MultiPageEditor.multiPageEditorMap.get(filePath);
			String resultStr = result.get("result")==null?"":(String)result.get("result");
			//resultStr = multi.doc.get();
			System.out.println("GET_EDITOR_VALUE1111:"+resultStr);
			resp.getWriter().write(resultStr);
			resp.getWriter().close();
		}
		if(SAVE_FILE.equals(type)){
			String filePath = req.getParameter("editfile");
			System.out.println("filePath:"+new String(filePath.getBytes("iso-8859-1"),"iso-8859-1"));
			filePath = java.net.URLDecoder.decode(filePath,"UTF-8"); 
			// System.out.println("filePath:"+filePath);
			String EditorValue = req.getParameter("EditorValue");
			
			String[] vals = EditorValue.replaceAll("\\\\|/|'|\"", " ").split(" ");
			System.out.println("vals:"+vals.length);
			
			// System.out.println("EditorValue"+EditorValue);
			//EditorValue = new String(EditorValue.getBytes("iso-8859-1"),"UTF-8");
			if(null!=filePath){
				IResource iresource = ResourcesPlugin.getWorkspace().getRoot().findMember(new Path(filePath));
				String exten = iresource.getFileExtension();
				if("eclick".equals(exten)){
					File editfile = iresource.getLocation().makeAbsolute().toFile().getAbsoluteFile();
					ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(editfile), 1024));
					zos.putNextEntry(new ZipEntry("daimabiji.html"));
					zos.write(EditorValue.getBytes("UTF-8"));
					for(int i=0;i<vals.length;i++){
						if(vals[i].endsWith(".jpg")){
							String path = Activator.plugin_path+"/webapps/manager/clientdata/"+vals[i];
							File jpg = new File(path);
							zos.putNextEntry(new ZipEntry(jpg.getName()));
							FileInputStream fis = new FileInputStream(jpg);
							byte[] JpgData = new byte[(int)jpg.length()];
							fis.read(JpgData);
							fis.close();
							zos.write(JpgData);
							//System.out.println(jpg.exists());
						}
					}
					zos.closeEntry();
					zos.flush();
					zos.close();
					resp.getWriter().write("OK");
					resp.getWriter().close();
					try {
						iresource.refreshLocal(IResource.DEPTH_ONE, null);
					} catch (CoreException e) {
						e.printStackTrace();
					}
				}
				
			}
			
		}
		
	}
	
	public static void main(String[] args){
		System.out.println("clientData/sssasdsada.jpg'".replaceAll("\\\\|/|'|\"", " "));
		
	}
	

}
